# -*- coding: utf-8 -*-

# File Name : flask_util
# Description :
# Author : marje
# date : 2022/6/7
# Change Activity : 2022/6/7
import base64
import os

import cv2
import numpy as np

import ml
from . import join_relative_path, create_dir, delete_file
from .random_util import get_uuid_str
from ...cv.misc.img_io import read_img


class FlaskUtil:
    tmp_image_file = 'files/img'

    @staticmethod
    def get_upload_image(request):
        """
        Parse image from request.
        Args:
            request:  flask request.

        Returns:

        """
        files = request.files
        upload_dir = join_relative_path(FlaskUtil.tmp_image_file)
        create_dir(upload_dir)
        for f in files:
            file = files[f]
            name = get_uuid_str() + '.jpg'
            image_path = os.path.join(upload_dir, name)
            file.save(image_path)
            img = read_img(image_path)
            delete_file(image_path)
            return img

    @staticmethod
    def get_base64_image_from_request(request):
        """
        get image from request
        :param request:
        :return:
        """
        try:
            img_str = str(request.data, 'utf8')
            img_decode_ = img_str.encode('ascii')
            img_decode = base64.b64decode(img_decode_)
            img_np = np.frombuffer(img_decode, np.uint8)
            img = cv2.imdecode(img_np, cv2.COLOR_RGB2BGR)
        except Exception as e:
            ml.logger.error('load image error:' + str(e))
            return None
        return img
